﻿using Prism.Ioc;
using System.Windows;

namespace Common.Prism.Services
{
    public class WindowsProviderService
    {
        private readonly IContainerProvider _serviceProvider;

        public WindowsProviderService(IContainerProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 关闭一个窗口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void Close<T>() where T : Window
        {
            Window windowInstance = GetInstanceWindows<T>();
            if (windowInstance != null)
            {
                windowInstance.Close();
            }
        }

        /// <summary>
        /// 显示一个窗口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void Show<T>(bool main = false) where T : Window
        {
            Window windowInstance = GetInstanceWindows<T>();

            if (windowInstance != null)
            {
                windowInstance.Activate();
            }
            else
            {
                windowInstance = _serviceProvider.Resolve<T>();
                if (main)
                {
                    Application.Current.MainWindow = windowInstance;
                }
                else
                {
                    windowInstance.Owner = Application.Current.MainWindow;
                }
                windowInstance.Show();
                windowInstance.Activate();
            }
        }

        /// <summary>
        /// 获取已存在的窗口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public Window GetInstanceWindows<T>()
        {
            foreach (Window item in Application.Current.Windows)
            {
                if (item is T)
                {
                    return item;
                }
            }
            return null;
        }

        /// <summary>
        /// 关闭一个窗口
        /// </summary>
        /// <param name="vm"></param>
        public void CloseByViewModel(object vm)
        {
            foreach (Window item in Application.Current.Windows)
            {
                if (item.DataContext == vm)
                {
                    item.Close();
                    return;
                }
            }
        }
    }
}
